<template>
  <el-dialog v-model="drawer" :append-to-body="true" width="880px" :title="type == 0?'发货申请':'发货通知单'" @close="close" destroy-on-close custom-class="logisticDetail">
    <el-form size="small" :model="form" :rules="rules" label-width="90px" ref="ruleRefForm">
        <el-row :gutter="20" class="page-content">
            <el-col :span="8">
                <el-form-item v-if="type == 0" label="订单号：">{{form.orderSn || '-'}}</el-form-item>
                <el-form-item v-else label="订单编号：">{{form.id || '-'}}</el-form-item>
            </el-col>
            <el-col :span="8" v-if="type != 0">
                <el-form-item label="物流公司：" prop="deliveryCompany">
                    <el-select v-if="type == 1"  v-model="form.deliveryComCode" placeholder="请选择物流公司" size="small" style="width: 252px;" filterable remote @change="companyChoose($event)">
                        <el-option
                            v-for="item in companyList"
                            :key="item.code"
                            :label="item.company"
                            :value="item.code"
                        />
                    </el-select>
                    <span v-else>{{ form.deliveryCompany }}</span>
                </el-form-item>
            </el-col>
            <el-col :span="8" v-if="type != 0">
                <el-form-item label="快递单号：" prop="logisticCode">
                    <el-input v-if="type == 1"  size="small" placeholder="请输入" v-model="form.logisticCode" style="width: 252px;"></el-input>
                    <span v-else>{{ form.logisticCode }}</span>
                </el-form-item>
            </el-col>
            <el-col :span="18" v-if="type != 2">
                <el-form-item label="联系人：" >
                    {{ form.receiverName }} - {{ form.receiverPhone }}
                </el-form-item>
            </el-col>
            <el-col :span="18" v-if="type != 2">
                <el-form-item label="收货地址：" >
                    {{ form.receiverProvince }}{{ form.receiverCity }}{{ form.receiverRegion }}{{ form.receiverDetailAddress }}
                </el-form-item>
            </el-col>
            <el-col :span="24" style="margin-top: 20px;">
                <el-table :data="form.orderItemList" size="small" border @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" :selectable="selectable" v-if="type != 2"/>
                    <el-table-column label="产品图" prop="spuPic" width="120px" align="center">
                        <template #default="scope">
                            <!-- <el-image style="width: 30px; height: 30px" :src="scope.row.spuPic" fit="cover" :preview-src-list="[scope.row.spuPic]" :preview-teleported="true" >
                                <template #error>
                                    <div class="image-slot">
                                        <el-icon><ele-Picture /></el-icon>
                                    </div>
                                </template>
                            </el-image> -->
                            <img style="width: 30px; height: 30px" :src="scope.row.spuPic" fit="cover">
                        </template>
                    </el-table-column>
                    <el-table-column label="产品名称" prop="spuName" :width="type != 2?'120px':'300px'"></el-table-column>
                    <el-table-column label="规格/详情" prop="skuName" :width="type != 2?'140px':'360px'"></el-table-column>
                    <el-table-column label="数量" prop="skuQuantity" align="center" width="60px"></el-table-column>
                    <el-table-column v-if="type == 0" label="单价(元)" prop="skuPrice" align="center" width="65px"></el-table-column>
                    <el-table-column v-if="type == 0" label="总价(元)" prop="realAmount" align="center" width="65px">
                        <template #default="scope">
                            {{scope.row.skuPrice * scope.row.skuQuantity}}
                        </template>
                    </el-table-column>
                    <el-table-column v-if="type == 1" label="已发" prop="actualNum" align="center" width="60px">
                        <template #default="scope">
                            {{ verifySendNum(scope.row, 1) }}
                        </template>
                    </el-table-column>
                    <el-table-column v-if="type == 0" label="已申请" prop="needNum" align="center" width="60px">
                        <template #default="scope">
                            {{ verifySendNum(scope.row, 0) }}
                        </template>
                    </el-table-column>
                    <el-table-column v-if="type == 1"  label="发货数量" prop="deliverNum" align="center" >
                        <template #default="scope">
                            <span v-if="scope.row.skuQuantity == scope.row.actualNum">已全部发货</span>
                            <el-input-number v-else v-model="scope.row.deliverNum" :min="1" :max="scope.row.skuQuantity - scope.row.actualNum" size="small" @change="alterApplyNum($event, scope.$index, scope.row.skuId)"/>
                        </template>
                    </el-table-column>
                    <el-table-column v-if="type == 0" label="申请数量" prop="deliverNum" align="center" >
                        <template #default="scope">
                            <span v-if="scope.row.skuQuantity == scope.row.needNum">已申请发货</span>
                            <el-input-number v-else v-model="scope.row.deliverNum" :min="1" :max="scope.row.skuQuantity - scope.row.needNum" size="small" @change="alterApplyNum($event, scope.$index, scope.row.skuId)"/>
                        </template>
                    </el-table-column>
                </el-table>
                <el-form-item v-if="type == 0" label="合计" style="margin-bottom:0;border-bottom:1px solid var(--el-border-color-light);font-size:14px;color:var(--el-color-danger)">{{form.totalAmount || '-'}}</el-form-item>
                <el-form-item v-if="type == 0" label="大写" style="margin-bottom:0;border-bottom:1px solid var(--el-border-color-light);font-weight:bold;font-size:14px;">{{getCaps(form.totalAmount || 0)}}</el-form-item>
                <el-form-item label="备注" style="margin-bottom:0;">{{form.note || '-'}}</el-form-item>
            </el-col>
            <el-col v-if="type != 0" :span="24" style="margin-top: 20px;">
                <el-form-item v-if="type == 1" label="选择出货地址" prop="area">
                    <el-cascader
                        ref="areaTree"
                        v-model="area"
                        :options="citys"
                        :props="props"
                        @change="handleChange"
                        style="width:593px"
                    />
                </el-form-item>
                <el-form-item v-if="type == 1" label="发货地址" prop="sendAddress">
                    <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入" v-model="form.sendAddress"></el-input>
                </el-form-item>

                
                
                <!-- 虚线 -->
                <el-row class="dotted-line" v-if="type == 2">
                    <el-col :span="24">
                        <el-form-item  label="发货日期：" >
                            {{ form.sendTime }}
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item  label="发货人：" >
                            {{ form.sendTime }}
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item  label="发货单号：" >
                            {{ form.sendSn }}
                        </el-form-item>
                    </el-col>
                </el-row>
                
                <!-- 实线 -->
                <div class="solid-border" v-if="type == 2">
                    <el-form-item label="联系人：" >
                        {{ form.receiverName }} - {{ form.receiverPhone }}
                    </el-form-item>
                    <el-form-item label="收货地址：" >
                        {{ form.receiverProvince }}{{ form.receiverCity }}{{ form.receiverRegion }}{{ form.receiverDetailAddress }}
                    </el-form-item>
                    <el-form-item label="发货人" prop="sendAddress">
                        <div>{{ form.sendUserName }}</div>
                    </el-form-item>
                    <el-form-item label="发货地址：">
                        <div>
                            <div>{{ form.receiverProvince }} - {{ form.receiverCity }} - {{ form.receiverRegion }}</div>
                            <div>{{ form.receiverDetailAddress }}</div>
                        </div>
                    </el-form-item>
                </div>
            </el-col>
        </el-row>
        <el-form-item style="margin-top: 20px;">
            <div style="width: 100%; display: flex; justify-content: center;">
                <el-button v-if="type == 0" :disabled="deliveryList.length == 0" size="small" type="primary" @click="submitApply(ruleRefForm)">发货申请</el-button>
                <el-button v-if="type == 1" :disabled="deliveryList.length == 0" size="small" type="primary" @click="submitForm(ruleRefForm)">提交</el-button>
                <el-button v-if="type == 2" size="small" type="primary" @click="printPage">打印快递单</el-button>
                <el-button size="small" @click="cancelForm(ruleRefForm)">取消</el-button>
            </div>
        </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { computed, reactive, toRefs, ref, onMounted, watch, nextTick, getCurrentInstance } from 'vue'
import { useOrderApi } from '/@/api/order/index'
import { useUserInfo } from '/@/stores/userInfo'
import { storeToRefs } from 'pinia';
import domtoimage from 'dom-to-image'
import { verifyNumberCnUppercase } from '/@/utils/toolsValidate'
import { ElMessage } from 'element-plus'
import { city } from '/@/utils/city'
import imgToBase64 from '/@/utils/imgToBase64'
import api from '/@/api/commonApi'

export default {
    name: 'LogisticDetail',
    props: {
        dialogDrawer: {
            type: Boolean,
            default: false
        },
        defaultForm: {
            type: Object,
            default: () =>  {
                return {}
            }
        },
        defaultType: {
            type: Number,
            default: 0
        }
    },
    emits: ['onSubmit', 'update:dialogDrawer'],
    setup(props, context){
        const { dialogDrawer, defaultForm, defaultType } = toRefs(props)
        const orderApi = useOrderApi()
        const storeUserInfo = useUserInfo() // 订单各类状态数据
        const { userInfos } = storeToRefs(storeUserInfo)
        const { proxy } = getCurrentInstance()
        const drawer = computed({
            get: () => dialogDrawer.value,
            set: val => {
                context.emit('update:dialogDrawer', val)
            }
        })
        watch(() => dialogDrawer.value,
            val => {
                if(val){
                    nextTick(() => {
                        getArea()
                    })
                }
            }
        )
        const form = computed({
            get: () => {
                if(defaultForm.value.orderItemList.length > 0){
                    defaultForm.value.orderItemList.forEach(item => {
                        if (defaultType.value == 1) {
                            item.deliverNum = item.needNum - item.actualNum
                        }else {
                            item.deliverNum = item.skuQuantity - item.needNum
                        }
                    })
                }
                return defaultForm.value
            },
            set: val => {
                context.emit('update:defaultForm', val)
            }
        })
        const type = computed({
            get: () => {
                if (defaultType.value == 1) {
                    state.rules = {
                        logisticCode: [{ required: true, message: '请输入快递单号', trigger: 'blur' }],
                        deliveryCompany: [{ required: true, message: '请输入物流公司', trigger: 'blur' }],
                    }
                }
                return defaultType.value
            },
            set: val => {
                context.emit('update:defaultType', val)
            }
        })
        const ruleRefForm = ref()
        const state = reactive({
            printImage: null,
            showImage: false,
            rules: {},
            form: {
                sendUserId: userInfos.value.id,
                sendUserName: userInfos.value.userName,
                deliveryComCode: '',
                deliveryCompany: ''
            },
            companyList: [],
            deliveryList: [],
            citys: city,
            area: [],
            props: {
                expandTrigger: 'hover',
                value: 'code'
            },
        })
        const close = () => {
            context.emit('update:dialogDrawer', false)
        }
        // 发货申请
        const submitApply = formEl => {
            let applyProductList = []
            state.deliveryList.forEach(item => {
                applyProductList.push({
                    orderId: item.orderId,
                    spuId: item.spuId,
                    spuName: item.spuName,
                    skuId: item.skuId,
                    skuName: item.skuName,
                    skuImg: item.skuImg,
                    needNum: item.deliverNum
                })                
            })
            let data = {
                orderId: form.value.id,
                assignCompany: 0,
                companyName: '',
                receiverName: form.value.receiverName,
                receiverPhone: form.value.receiverPhone,
                receiverProvince: form.value.receiverProvince,
                receiverCity: form.value.receiverCity,
                receiverRegion: form.value.receiverRegion,
                receiverAddress: form.value.receiverDetailAddress,
                belongerId: form.value.belongerId,
                belongerName: '',
                applyProductList: applyProductList
            }
            console.log(data);
            api.applyForDelivery(data).then(res => {
                ElMessage.success('已提交申请')
                state.deliveryList = []
                context.emit('onSubmit', true)
                context.emit('update:dialogDrawer', false)
            })
        }
        // 仓库发货
        const submitForm = formEl => {   
            console.log(state.deliveryList);         
            if (!formEl) return
            formEl.validate((valid) => {
                if (valid) {
                    let data = {
                        orderId: form.value.id,
                        deliverySn: form.value.logisticCode,
                        deliveryComCode: form.value.deliveryComCode,
                        deliveryCompany: form.value.deliveryCompany,
                        sendProvince: form.value.sendProvince,
                        sendCity: form.value.sendCity,
                        sendRegion: form.value.sendRegion,
                        sendAddress: form.value.sendAddress,
                        applyId: form.value.applyId,
                        skuItems: state.deliveryList,
                        returnApplyId: form.value.returnApplyId,
                    }
                    orderApi.sendDelivery(data).then(res => {
                        ElMessage.success('发货成功')
                        state.deliveryList = []
                        context.emit('onSubmit', true)
                        context.emit('update:dialogDrawer', false)
                    })
                }
            })
        }
        // 取消
        const cancelForm = formEl => {
            if (!formEl) return
            formEl.resetFields()
            context.emit('update:dialogDrawer', false)
        }
        const getCompanyList = () => {
            api.companyList().then(res => {
                state.companyList = res.data
            })
        }
        const companyChoose = (e) => {
            let map = state.companyList.find(item => item.code == e)
            state.form.deliveryCompany = map.company
            form.value.deliveryCompany = map.company
        }
        // 获取大写
        const getCaps = computed(() => {
            return price => {
                return verifyNumberCnUppercase(price)
            }
        })
        const handleSelectionChange = (val) => {
            console.log(val);
            state.deliveryList = []
            if (val.length > 0) {
                val.forEach(item => {
                    state.deliveryList.push({
                        orderId: item.orderId,
                        spuId: item.spuId,
                        spuName: item.spuName,
                        skuId: item.skuId,
                        skuName: item.skuName,
                        skuImg: item.spuPic,
                        skuDesc: item.skuAttrsVals,
                        skuPrice: item.skuPrice,
                        deliverNum: item.deliverNum
                    })
                })
            }
        }
        const verifySendNum = (item, type) => {
            if (type == 1) {
                return item.actualNum
            }else {
                return item.needNum
            }
        }
        const selectable = (row, index, skuId) => {
            if (type.value == 0) {
                return row.skuQuantity > (row.needNum ? row.needNum : 0)
            }
            return row.skuQuantity > (row.actualNum ? row.actualNum : 0)
        }
        const alterApplyNum = (val, index, skuId) => {
            if (state.deliveryList.length > 0) {
                state.deliveryList.forEach(item => {
                    if(item.skuId == skuId) {
                        item.deliverNum = val
                    }
                })
            }
            form.value.orderItemList[index].deliverNum = val
        }
        const handleChange = () => {
            const area = proxy.$refs['areaTree'].getCheckedNodes()[0].pathLabels
            form.value.sendProvince = area[0]
            form.value.sendCity = area[1]
            form.value.sendRegion = area[2]
        }
        const getArea = () => { // 省市区数据筛选
            const provinceList = state.citys.find(item => {
                return item.label == state.form.receiverProvince
            })
            let area = []
            if(provinceList){
                area[0] = provinceList.code
                const citysList = provinceList.children.find(item => {
                    return item.label == state.form.receiverCity
                })
                if(citysList){
                    area[1] = citysList.code
                    const areaList = citysList.children.find(item => {
                        return item.label == state.form.receiverRegion
                    })
                    if(areaList){
                        area[2] = areaList.code
                    }
                }
            }
            state.area = area
        }
        const printPage = async() => {
            const content = document.querySelector('.page-content')
            state.showOptions = false
            if(state.printImage) {
                state.showImage = true
                setTimeout(() => {
                    window.print()
                    state.showImage = false
                }, 150)
                return
            }
            
            const imgList = content.querySelectorAll("img")
            for (let i = 0; i < imgList.length; i++) {
                await imgToBase64(imgList[i].currentSrc).then(res => {
                    imgList[i].attributes[0].value = res
                })
            }
            
            await domtoimage.toBlob(content, {
                bgcolor: 'white',
                quality: 1,
            }).then((dataUrl) => {
                console.log(dataUrl);
                state.printImage = URL.createObjectURL(dataUrl)
                state.showImage = true
                if(dataUrl) {
                    nextTick(async () => {
                        setTimeout(() => {
                            window.print()
                            state.showImage = false
                        }, 150)
                    })
                }
            })
        }

        onMounted(() => {
            getCompanyList()
        })
        return {
            ...toRefs(state),
            drawer,
            form,
            type,
            close,
            getArea,
            getCaps,
            printPage,
            selectable,
            verifySendNum,
            ruleRefForm,
            submitForm,
            submitApply,
            cancelForm,
            onMounted,
            companyChoose,
            getCompanyList,
            alterApplyNum,
            handleChange,
            handleSelectionChange,

        }
    }
}
</script>

<style>
.dotted-line {
    border: 1px dashed #c0c4cc;
    padding: 20px 0;
}

.solid-border {
    margin-top: 40px;
    border: 1px solid #c0c4cc;
    padding: 20px 0;
}
</style>